<?php
/**
 * This file is part of Swoft.
 *
 * @link     https://swoft.org
 * @document https://swoft.org/docs
 * @contact  group@swoft.org
 * @license  https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

use Swoft\Context\Context;
use Swoft\Http\Message\ContentType;
use Swoft\Http\Message\Response;
use Firebase\JWT\JWT;

function json($data, int $code = 200): Response
{
    if (is_string($data) && $code != 200) {
        $data = ['msg' => $data];
    }
    return Context::get(true)->getResponse()->withStatus($code)->withContentType(ContentType::JSON)->withData($data);
}

function makeToken(array $user)
{
    $time  = time();
    $token = [
        "iat"  => $time,//签发时间
        //"ext"  => 86400,//过期时间
        "data" => $user
    ];
    return JWT::encode($token, config('jwt.key'), config('jwt.type'));
}

function checkToken(string $str)
{
    $decoded = JWT::decode($str, config('jwt.key'), [config('jwt.type')]);
    return (array)$decoded->data;
}
